package org.jeecg.common.system.base.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.function.DictItemValueGenerator;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.FileInfo;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: Controller基类
 * @Author: dangzhenghui@163.com
 * @Date: 2019-4-21 8:13
 * @Version: 1.0
 */
@Slf4j
public class JeecgController<T, S extends IService<T>> {
    @Autowired
    protected S service;

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    protected ISysBaseAPI sysBaseApi;

    @Autowired
    protected RedisTemplate redisTemplate;

    /**
     * 数据字典值自增生成
     */
    protected DictItemValueGenerator<String, String> generator = code -> {
        List<DictModel> models = sysBaseApi.queryDictItemsByCode(code);
        models.sort(Comparator.comparing(DictModel::getValue).reversed());
        int value = Convert.toInt(models.get(0).getValue());
        return Convert.toStr(value + 1);
    };

    /**
     * 编号生成
     */
    protected DictItemValueGenerator<String, Integer> noGenerator = length -> {
        int year = DateUtil.year(DateUtil.date());
        String no = "";
        long r = 0;
        while (r == 0) {
            no = year + RandomStringUtils.randomNumeric(length);
            r = redisTemplate.opsForSet().add("RANDOM_NO", no);
        }
        return no;
    };

    /**
     * 导出excel
     *
     * @param request
     */
    protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) {
        // Step.1 组装查询条件
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<T> pageList = service.list(queryWrapper);
        List<T> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导出
     *
     * @param params
     * @param clz
     * @param data
     * @return
     */
    @SneakyThrows
    public String exportXls(ExportParams params, Class<?> clz, List<?> data) {
        Workbook workbook = ExcelExportUtil.exportExcel(params, clz, data);
        @Cleanup ByteArrayOutputStream stream = new ByteArrayOutputStream();
        workbook.write(stream);
        String savePath = sysBaseApi.uploadToLocal(stream.toByteArray(), "excel", "file.xls");
        String uuid = IdUtil.fastSimpleUUID();
        String url = "/sys/common/static/" + uuid;
        List<DictModel> models = sysBaseApi.queryDictItemsByCode("download_expir_time");
        FileInfo fileInfo = new FileInfo(savePath, params.getTitle() + ".xls");
        redisUtil.set(CommonConstant.DOWNLOAD_TOKEN + uuid, fileInfo, Convert.toInt(models.get(0).getValue()));
        return url;
    }

    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(T item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                service.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    public String sort(String key, int seed) {
        RedisAtomicLong atomicLong = null;
        if (redisTemplate.hasKey(key)) {
            atomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        } else {
            atomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory(), seed);
        }
        long incr = atomicLong.getAndIncrement();
        String no = incr < 1000 ? String.format("%04d", incr) : String.valueOf(incr);
        return no;
    }


    protected String toUnderlineName(String s) {
        if (s == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean nextUpperCase = true;

            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }

            if ((i >= 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    if (i > 0) {
                        sb.append("_");
                    }
                }
                upperCase = true;
            } else {
                upperCase = false;
            }

            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * 添加字典项
     *
     * @param code      字典编码
     * @param text      字典文本
     * @param generator 字典值生成器
     * @return
     */
    protected String addDictItem(String code, String text, DictItemValueGenerator<String, String> generator) {
        List<DictModel> models = sysBaseApi.queryDictItemsByCode(code);
        DictModel m = models.stream().filter(model -> StringUtils.equals(model.getText(), text)).findFirst().orElse(null);
        if (m != null) {
            return m.getValue();
        }
        String val = generator.generator(code);
        DictModel model = new DictModel();
        model.setCode(code);
        model.setValue(val);
        model.setText(text);
        sysBaseApi.addDictItem(model);
        return val;
    }


    /**
     * 属性值是否重复
     *
     * @return
     */
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        QueryWrapper<T> wrapper = Wrappers.query();
        if (StringUtils.isNotBlank(params.getId())) {
            wrapper.ne("id", params.getId());
        }
        wrapper.eq("del_flag", false);
        String msg = "";
        String[] property = ArrayUtil.toArray(params.getProperty(), String.class);
        String[] value = ArrayUtil.toArray(params.getValue(), String.class);
        for (int i = 0; i < property.length; i++) {
            wrapper.eq(toUnderlineName(property[i]), value[i]);
            int count = service.count(wrapper);
            if (count > 0) {
                msg = value[i] + "已存在";
                break;
            }
        }

        return StringUtils.isNotBlank(msg) ? Result.error(msg) : Result.ok();
    }

    /**
     * word模版导出
     *
     * @param templateName 模版名称
     * @param sourceName   导出文件名
     * @param map          模版参数
     * @return
     */
    @SneakyThrows
    protected String exportWord(String templateName, String sourceName, Map<String, Object> map) {
        Document document = new Document();
        document.loadFromStream(new ClassPathResource("templates/" + templateName).getStream(), FileFormat.Docx);
        map.forEach((k, v) -> {
            TextSelection selection = document.findString("{" + k + "}", false, true);
            if (selection == null) {
                return;
            }
            TextRange range = selection.getAsOneRange();
            range.setText(Convert.toStr(v));
        });
        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.saveToStream(baos, FileFormat.Docx);
        document.close();
        String savePath = sysBaseApi.uploadToLocal(baos.toByteArray(), "word", "file.docx");
        String uuid = IdUtil.fastSimpleUUID();
        String url = "/sys/common/static/" + uuid;
        List<DictModel> models = sysBaseApi.queryDictItemsByCode("download_expir_time");
        FileInfo fileInfo = new FileInfo(savePath, sourceName);
        redisUtil.set(CommonConstant.DOWNLOAD_TOKEN + uuid, fileInfo, Convert.toInt(models.get(0).getValue()));
        return url;
    }

}
